﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using DigitalSolutionLibrary.SqlDatabase;
using DigitalSolutionLibrary.Utilities;

namespace DigitalSolutionManagement
{
    public partial class frmGantPermission : BaseFormEdit
    {
        private Thread th;
        private DataTable tbUnGant;
        private DataTable tbGant;
        private delegate void DelegFillCom(DataSet ds);
        private bool isLoaded;
        private int dragPos = -1;
        private string lstSourceName = String.Empty;

        #region prepare form
        private void PrepareForm()
        {
            //load role
            object obj = Program.dbWrapper.ExecuteStore("LoadEmpType", null, DatabaseWrapper.ReturnType.DATASET);
            if (obj != null)
            {
                DataSet ds = (DataSet)obj;
                DelegFillCom dfc = new DelegFillCom(FillCombo);
                Invoke(dfc, new object[] { ds });

                //load permision follow role
                LoadPermission();
            }
            else
            {
                processing1.HideProcessing();
                btnOK.Enabled = false;
                MessageBox.Show("Không thể kết nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            isLoaded = true;
        }
        #endregion

        #region fill combo
        private void FillCombo(DataSet ds)
        {
            cmbRole.DataSource = ds.Tables[0];
            cmbRole.DisplayMember = "TypeName";
            cmbRole.ValueMember = "TypeId";
        }
        #endregion

        #region load permision follow role
        private void LoadPermission()
        {
            ParameterStock stoc = new ParameterStock();
            Parameter par = new Parameter("RoleId", cmbRole.SelectedValue, SqlDbType.Int);
            stoc.AddParamter(par);

            object obj = Program.dbWrapper.ExecuteStore("LoadPermissionByRole", stoc, DatabaseWrapper.ReturnType.DATASET);
            if (obj != null)
            {
                DataSet dsp = (DataSet)obj;
                dsp.DataSetName = "Root";
                tbGant = dsp.Tables[0];
                tbUnGant = dsp.Tables[1];

                //add gant per to list
                lstGantPer.Items.Clear();
                foreach (DataRow row in tbGant.Rows)
                    lstGantPer.Items.Add(row["PerName"].ToString(), 0);

                //add ungant per to list
                lstUnGantPer.Items.Clear();
                foreach (DataRow row in tbUnGant.Rows)
                    lstUnGantPer.Items.Add(row["PerName"].ToString(), 0);

                processing1.HideProcessing();
                
            }
            else
            {
                processing1.HideProcessing();
                btnOK.Enabled = false;
                MessageBox.Show("Không thể kết nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region ok press
        private void OkPress()
        {
            tbGant.TableName = "Permisstion";
            ParameterStock stock = new ParameterStock();
            Parameter par = new Parameter("RoleId", cmbRole.SelectedValue, SqlDbType.Int);
            stock.AddParamter(par);

            par = new Parameter("XmlPer", Utility.DataTableToXml(tbGant), SqlDbType.Xml);
            stock.AddParamter(par);

            par = new Parameter("Message", null, SqlDbType.NVarChar, ParameterDirection.Output, 200);
            stock.AddParamter(par);

            object obj = Program.dbWrapper.ExecuteStore("UpdatePermissionRole", stock, DatabaseWrapper.ReturnType.FIRST_CELL);
            if (obj != null)
            {
                int rs = (int)obj;
                if (rs > 0)
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                else
                {
                    processing1.HideProcessing();
                    MessageBox.Show(stock.GetAtPosition(2).ValueOut.ToString(), "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                processing1.HideProcessing();
                MessageBox.Show("Không thể kết nối đến server, vui lòng thử lại sau", "DSCo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        public frmGantPermission()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            
        }

        private void frmGantPermission_Load(object sender, EventArgs e)
        {
            processing1.ShowProcessing();
            th = new Thread(() => PrepareForm());
            th.Start();
        }

        private void frmGantPermission_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (th != null && th.IsAlive)
                th.Abort();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            processing1.ShowProcessing();
            th = new Thread(() => OkPress());
            th.Start();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmEditRole frm = new frmEditRole(OpenMode.NEW);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                isLoaded = false;
                processing1.ShowProcessing();
                th = new Thread(() => PrepareForm());
                th.Start();
            }
        }

        private void cmbRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoaded)
            {
                processing1.ShowProcessing();
                th = new Thread(() => LoadPermission());
                th.Start();
            }
        }

        private void lstUnGantPer_DragDrop(object sender, DragEventArgs e)
        {
            if (lstSourceName == ((ListView)sender).Name)
                return;
            lstGantPer.Items.RemoveAt(dragPos);

            ListViewItem it = new ListViewItem();
            tbUnGant.Rows.Add(tbGant.Rows[dragPos]["PerId"], tbGant.Rows[dragPos]["PerName"]);
            it = (ListViewItem)e.Data.GetData(it.GetType().ToString());
            lstUnGantPer.Items.Add(it);

            tbGant.Rows.RemoveAt(dragPos);
        }

        private void lstUnGantPer_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void lstGantPer_DragDrop(object sender, DragEventArgs e)
        {
            if (lstSourceName == ((ListView)sender).Name)
                return;
            lstUnGantPer.Items.RemoveAt(dragPos);

            ListViewItem it = new ListViewItem();
            tbGant.Rows.Add(tbUnGant.Rows[dragPos]["PerId"], tbUnGant.Rows[dragPos]["PerName"]);
            lstGantPer.Items.Add(((ListViewItem)e.Data.GetData(it.GetType().ToString())));

            tbUnGant.Rows.RemoveAt(dragPos);
        }

        private void lstGantPer_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void lstUnGantPer_ItemDrag(object sender, ItemDragEventArgs e)
        {
            ListViewItem it = (ListViewItem)e.Item;
            dragPos = it.Index;
            lstSourceName = it.ListView.Name;
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void lstGantPer_ItemDrag(object sender, ItemDragEventArgs e)
        {
            ListViewItem it = (ListViewItem)e.Item;
            dragPos = it.Index;
            lstSourceName = it.ListView.Name;
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            frmEditRole frm = new frmEditRole(OpenMode.EDIT);
            frm.ItemId = (int)cmbRole.SelectedValue;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                isLoaded = false;
                processing1.ShowProcessing();
                th = new Thread(() => PrepareForm());
                th.Start();
            }
        }

    }
}
